package com.ch.mapdemo.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ch.mapdemo.entity.MapDemo;
import com.ch.mapdemo.entity.MapDemoExample;
import com.ch.mapdemo.service.MapDemoService;
import com.ch.mapdemo.util.HttpClientHelper;

@Controller
public class MapFanceController {
	
	@Autowired
	MapDemoService mapDemoService;
	/**
	 * 列表页面
	 * @return
	 */
	@GetMapping("/")
	public String list(){
		  
	    return "index";
	}
	/**
	 * 列表数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getList",method=RequestMethod.POST)
	public  Map<String,Object> getList(){
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		MapDemoExample mapDemoExample = new MapDemoExample();
		List<MapDemo> list = mapDemoService.selectByExample(mapDemoExample);
		resmap.put("data", list);
		resmap.put("result", result);
		return resmap;
	}
	/**
	 * 新增页面
	 * @return
	 */
	@GetMapping("/add")
	public String add(){
	      return "mapdraw";
	}
	/**
	 * 电子围栏创建多边形（矩形）
	 */
	@ResponseBody
	@RequestMapping(value="/saveGeofence",method=RequestMethod.POST)
	public Map<String,Object> saveGeofence(@RequestParam("points") String points,@RequestParam("type") String type) {
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		try {
			//调用围栏
			Map<String,Object> map = new HashMap<String,Object>();
			
			map.put("name", "测试围栏");
			map.put("points", points);
			map.put("enable", "true");
			map.put("valid_time", "2020-08-10");
			map.put("repeat", "Mon,Tues,Wed,Thur,Fri,Sat,Sun");
			map.put("alert_condition", "enter;leave");
			
			HttpClientHelper http = new HttpClientHelper();
			
			String reultht = http.sendPost("https://restapi.amap.com/v4/geofence/meta?key=417fe25389cf3e98207554cd362dc5cc", JSON.toJSONString(map));
			//保存围栏得id和坐标集合
			JSONObject jsonmap  = JSONObject.parseObject(reultht);
			
			if(resmap!=null&&"OK".equals(jsonmap.get("errmsg"))) {
				JSONObject jsonmapres  = JSONObject.parseObject(jsonmap.get("data").toString());
				if(jsonmapres!=null) {
					MapDemo mapDemo = new MapDemo();
					mapDemo.setMapGid(jsonmapres.get("gid").toString());
					mapDemo.setMapId(jsonmapres.get("id").toString());
					mapDemo.setPoints(points);
					mapDemo.setCreateTime(new Date());
					DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");   
					mapDemo.setValidTime(format1.parse("2020-08-10"));
					mapDemo.setMapType(type);
					mapDemoService.insertSelective(mapDemo);
				}
				
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			result = e.getMessage();
			System.err.println(e.getMessage());
		}
		
		resmap.put("result", result);
		return resmap;
		
	}
	
	/**
	 * 电子围栏创建多边形（圆形）
	 */
	@ResponseBody
	@RequestMapping(value="/saveGeofenceCircle",method=RequestMethod.POST)
	public Map<String,Object> saveGeofenceCircle(@RequestParam("center") String center,@RequestParam("radius") String radius) {
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		try {
			//调用围栏
			Map<String,Object> map = new HashMap<String,Object>();
			
			map.put("name", "测试围栏");
			map.put("center", center);
			map.put("radius", radius);
			
			map.put("enable", "true");
			map.put("valid_time", "2020-08-10");
			map.put("repeat", "Mon,Tues,Wed,Thur,Fri,Sat,Sun");
			map.put("alert_condition", "enter;leave");
			
			HttpClientHelper http = new HttpClientHelper();
			
			String reultht = http.sendPost("https://restapi.amap.com/v4/geofence/meta?key=417fe25389cf3e98207554cd362dc5cc", JSON.toJSONString(map));
			//保存围栏得id和坐标集合
			JSONObject jsonmap  = JSONObject.parseObject(reultht);
			
			if(resmap!=null&&"OK".equals(jsonmap.get("errmsg"))) {
				JSONObject jsonmapres  = JSONObject.parseObject(jsonmap.get("data").toString());
				if(jsonmapres!=null) {
					MapDemo mapDemo = new MapDemo();
					mapDemo.setMapGid(jsonmapres.get("gid").toString());
					mapDemo.setMapId(jsonmapres.get("id").toString());
					mapDemo.setPoints(center);
					mapDemo.setRadius(radius);
					DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");   
					mapDemo.setValidTime(format1.parse("2020-08-10"));
					mapDemo.setCreateTime(new Date());
					mapDemo.setMapType("circle");
					mapDemoService.insertSelective(mapDemo);
				}
				
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			result = e.getMessage();
			System.err.println(e.getMessage());
		}
		
		resmap.put("result", result);
		return resmap;
		
	}
	
	/**
	 * 新增页面
	 * @return
	 */
	@GetMapping("/goEdit")
	public String goEdit(){
	      return "editmapdraw";
	}
	
	/**
	 * 列表数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getMapDemo",method=RequestMethod.POST)
	public Map<String,Object> getMapDemo(@RequestParam("id") String id){
		
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		MapDemo mapDemo = mapDemoService.selectByPrimaryKey(Integer.parseInt(id));
		resmap.put("mapDemo", mapDemo);
		resmap.put("result", result);
		return resmap;
	}
	
	
	
	/**
	 * 电子围栏创建多边形（矩形）
	 */
	@ResponseBody
	@RequestMapping(value="/updateGeofence",method=RequestMethod.POST)
	public Map<String,Object> updateGeofence(@RequestParam("points") String points,@RequestParam("type") String type,@RequestParam("id") String id) {
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		try {
			
			MapDemo mapDemo = mapDemoService.selectByPrimaryKey(Integer.parseInt(id));
			if(mapDemo!=null) {
				//调用围栏
				Map<String,Object> map = new HashMap<String,Object>();
				
				map.put("name", "测试围栏");//设计表的时候可以保存到库中，然后直接取值
				map.put("points", points);
				map.put("enable", "true");
				map.put("valid_time", mapDemo.getValidTime());//可以弹框界面选择有效期
				map.put("repeat", "Mon,Tues,Wed,Thur,Fri,Sat,Sun");
				map.put("alert_condition", "enter;leave");
				map.put("desc", "更新测试");//更新说明
				
				HttpClientHelper http = new HttpClientHelper();
				
				String reultht = http.sendPost("https://restapi.amap.com/v4/geofence/meta?key=417fe25389cf3e98207554cd362dc5cc&gid="+mapDemo.getMapGid(), JSON.toJSONString(map));
				//保存围栏得id和坐标集合
				JSONObject jsonmap  = JSONObject.parseObject(reultht);
				
				if(resmap!=null&&"OK".equals(jsonmap.get("errmsg"))) {
						mapDemo.setPoints(points);
						//mapDemo.setCreateTime(new Date());//可以设计更新时间
						mapDemo.setMapType(type);
						mapDemoService.updateByPrimaryKeySelective(mapDemo);
					
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			result = e.getMessage();
			System.err.println(e.getMessage());
		}
		
		resmap.put("result", result);
		return resmap;
		
	}
	
	/**
	 * 电子围栏创建多边形（圆形）
	 */
	@ResponseBody
	@RequestMapping(value="/updateGeofenceCircle",method=RequestMethod.POST)
	public Map<String,Object> updateGeofenceCircle(@RequestParam("center") String center,@RequestParam("radius") String radius,@RequestParam("id") String id) {
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		try {
			MapDemo mapDemo = mapDemoService.selectByPrimaryKey(Integer.parseInt(id));
			if(mapDemo!=null) {
				//调用围栏
				Map<String,Object> map = new HashMap<String,Object>();
				
				map.put("name", "测试围栏");
				map.put("center", center);
				map.put("radius", radius);
				
				map.put("valid_time", mapDemo.getValidTime());//可以弹框界面选择有效期
				map.put("repeat", "Mon,Tues,Wed,Thur,Fri,Sat,Sun");
				map.put("alert_condition", "enter;leave");
				map.put("desc", "更新测试");//更新说明
				HttpClientHelper http = new HttpClientHelper();
				
				String reultht = http.sendPost("https://restapi.amap.com/v4/geofence/meta?key=417fe25389cf3e98207554cd362dc5cc&gid="+mapDemo.getMapGid(), JSON.toJSONString(map));
				//保存围栏得id和坐标集合
				JSONObject jsonmap  = JSONObject.parseObject(reultht);
				
				if(resmap!=null&&"OK".equals(jsonmap.get("errmsg"))) {
						mapDemo.setPoints(center);
						mapDemo.setRadius(radius);
						mapDemo.setMapType("circle");
						mapDemoService.updateByPrimaryKeySelective(mapDemo);
					
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			result = e.getMessage();
			System.err.println(e.getMessage());
		}
		
		resmap.put("result", result);
		return resmap;
		
	}
	/**
	 * 删除电子围栏
	 */
	@ResponseBody
	@RequestMapping(value="/delGeofence",method=RequestMethod.GET)
	public Map<String,Object> delGeofence(@RequestParam("id") String id) {
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		try {
			MapDemo mapDemo = mapDemoService.selectByPrimaryKey(Integer.parseInt(id));
			if(mapDemo!=null) {
				//调用围栏
				Map<String,Object> map = new HashMap<String,Object>();
			
				HttpClientHelper http = new HttpClientHelper();
				
				String reultht = http.sendPost("https://restapi.amap.com/v4/geofence/meta?key=417fe25389cf3e98207554cd362dc5cc&gid="+mapDemo.getMapGid()+"&method=delete", JSON.toJSONString(map));
				//保存围栏得id和坐标集合
				JSONObject jsonmap  = JSONObject.parseObject(reultht);
				
				if(resmap!=null&&"OK".equals(jsonmap.get("errmsg"))) {
					mapDemoService.deleteByPrimaryKey(Integer.parseInt(id));
					
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			result = e.getMessage();
			System.err.println(e.getMessage());
		}
		
		resmap.put("result", result);
		return resmap;
		
	}
	
	/**
	 * 电子围栏启动停止
	 */
	@ResponseBody
	@RequestMapping(value="/goOnGeofence",method=RequestMethod.GET)
	public Map<String,Object> goOnGeofence(@RequestParam("id") String id) {
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		try {
			MapDemo mapDemo = mapDemoService.selectByPrimaryKey(Integer.parseInt(id));
			if(mapDemo!=null) {
				//调用围栏
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("enable", true);//true 启动 false 停止
			
				HttpClientHelper http = new HttpClientHelper();
				
				String reultht = http.sendPost("https://restapi.amap.com/v4/geofence/meta?key=417fe25389cf3e98207554cd362dc5cc&gid="+mapDemo.getMapGid()+"&&method=patch", JSON.toJSONString(map));
				//保存围栏得id和坐标集合
				JSONObject jsonmap  = JSONObject.parseObject(reultht);
				
				if(resmap!=null&&"OK".equals(jsonmap.get("errmsg"))) {
					//mapDemo.set 数据库存有启动状态的进行更新
					//mapDemoService.updateByPrimaryKeySelective(mapDemo);
					
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			result = e.getMessage();
			System.err.println(e.getMessage());
		}
		
		resmap.put("result", result);
		return resmap;
		
	}
	
	/**
	 * 查询是否存在电子围栏内
	 */
	@ResponseBody
	@RequestMapping(value="/isGeofence",method=RequestMethod.GET)
	public Map<String,Object> isGeofence(@RequestParam("id") String id) {
		Map<String,Object> resmap = new HashMap<String,Object>();
		String result = "success";
		try {
			MapDemo mapDemo = mapDemoService.selectByPrimaryKey(Integer.parseInt(id));
			if(mapDemo!=null) {
				//调用围栏
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("key", "417fe25389cf3e98207554cd362dc5cc");
				map.put("diu", "A0000084A2DD73");//设备唯一标识符，作为记录依据，不影响判断结果。Android设备一般使用imei号码，iOS一般使用idfv号，其余设备可根据业务自定义。
				map.put("locations", "116.472407,39.993322,1584816232");//当前设备的坐标至少包含一个坐标对和时间戳格式: x1,y1,unix_ts1;x2,y2,unix_ts2
			
				HttpClientHelper http = new HttpClientHelper();
				
				String reultht = http.sendPost("https://restapi.amap.com/v4/geofence/status?key=417fe25389cf3e98207554cd362dc5cc&diu=A0000084A2DD73&locations=116.472407,39.993322,1584816232", JSON.toJSONString(map));
				//保存围栏得id和坐标集合
				reultht = "{\"data\": {\"fencing_event_list\": [{\"client_action\": \"enter\",\"client_status\": \"in\",\"enter_time\": \"2017-01-19 16:57:12\",\"fence_info\": {\"fence_center\": \"116.47253,39.992912\",\"fence_gid\": \"31c94518-4145-4a94-9e7d-34cb027b4c96\",\"fence_name\": \"测试大围栏\"}}],\"status\": 0},\"errcode\": 0,\"errmsg\": \"OK\"}";
				JSONObject jsonmap  = JSONObject.parseObject(reultht);
				
				if(resmap!=null&&"OK".equals(jsonmap.get("errmsg"))) {
					JSONObject jsonmapres  = JSONObject.parseObject(jsonmap.get("data").toString());
					JSONArray jsonmapres1 =  JSONObject.parseArray(jsonmapres.get("fencing_event_list").toString());
					for (Object object : jsonmapres1) {
						Map entry = (Map)object;
						JSONObject jsonmapr = JSONObject.parseObject(entry.get("fence_info").toString());
						if(mapDemo.getMapGid().equals(jsonmapr.get("fence_gid"))) {
							//业务处理
							//同一个围栏，查看状态值entry.get("client_status");--设备状态。当前与围栏的静态关系状态。是否在围栏里： in|out 
							//entry.get("client_action");--设备行为。对应3种与围栏的动态交互关系，进/出/停留： enter|leave|stay
						}
					}
					
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			result = e.getMessage();
			System.err.println(e.getMessage());
		}
		
		resmap.put("result", result);
		return resmap;
		
	}
	
	
	
	

}
